import React, { ChangeEvent, FC, useEffect, useRef, useState, useCallback } from "react";
import './index.css'
import { Button, Drawer, message, Select, Spin, Table, Tag } from 'antd';
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import { useRequest } from "@umijs/hooks";
import XLSX from "xlsx";
import { getOriginString, getSecretString } from "@/utils/encrypt";
import { FallOutlined, SearchOutlined } from "@ant-design/icons";
// @ts-ignore
import shortid from 'shortid'
import { LoadingOutlined } from '@ant-design/icons';
const { Option } = Select;

const stateList = [
  {
    text: '等待开通',
    className: 'loading-open'
  },
  {
    text: '开通成功',
    className: 'success-open'
  }
  ,
  {
    text: '开通失败',
    className: 'error-open'
  }
]


const columns = [
  {
    title: '学生姓名',
    key: 'student_name',
    dataIndex: 'student_name',
  },
  {
    title: '学生电话',
    key: 'phone',
    dataIndex: 'phone',
    render: (phone: any) => <>{getOriginString(phone)}</>

  },
  {
    title: '白卡号',
    key: 'white_card_code',
    dataIndex: 'white_card_code',
  },
  {
    title: 'imei号',
    key: 'imei',
    dataIndex: 'imei',
  },
  {
    title: '门禁描述',
    key: 'remark',
    dataIndex: 'remark',
  },

  {
    title: '状态',
    key: 'state',
    dataIndex: 'state',
    render: (state: number) => <div className={stateList[state].className}>{stateList[state].text}</div>
  }
]

interface ICollegeAreaList {
  collegeAreaId: number,
  collegeId: number,
  collegeAndArea?: string
}

const paramsTemp = {
  collegeAreaId: '',
  collegeId: '',
  fileName: '',
  studentAccessList: [] as any[]
}

const Index: FC = () => {


  const params = useRef({ ...paramsTemp })

  const batchListParams = useRef({
    pageStart: 1,
    pageSize: 10,
    loading: false,
    total: 0
  })
  const selectBatch = useRef(0)


  const [batchList, setBatchList] = useState<any[]>([])
  const [visible, setVisible] = useState(false)

  const flag = useRef(false)
  const [data, setData] = useState<any>([])

  const {
    tableProps,
    run,
  } = useRequest(((current, batch) => fetchRequest(url.BATCH_TABLE, {
    pageSize: current.pageSize,
    pageStart: current.current,
    batch

  })), {
    paginated: true,
    manual: true,
    formatResult: (response: any) => {
      return {
        list: response.importDataVos.rows,
        total: response.importDataVos.total
      };
    }
  })

  const [id, setId] = useState('')
  const [loading, setLoading] = useState(false)

  const ImportClick = () => {
    setVisible(true)

  }

  const selectClick = async () => {
    await run({ pageSize: 10, current: 1 }, selectBatch.current)
  }


  const importData = async () => {


    const { success, error } = await fetchRequest(url.IMPORT_ALL_DATA, { ...params.current })
    if (!success) {
      message.error(error)
      setLoading(false)
      return
    }

    message.success('导入成功')
    setLoading(false)
    setVisible(false)
    params.current.collegeAreaId = ''
    params.current.collegeId = ''
    params.current.fileName = ''
    setData([])



  }


  const selectBatchList = useCallback(async (params: any) => {
    const data = await fetchRequest(url.BATCH_SELECT, params)
    if (data.success) {

      setBatchList((list: any[]) => [...list, ...data?.importDataBatchVOMyPager?.rows])
      batchListParams.current.total = data?.importDataBatchVOMyPager?.total


    }
    batchListParams.current.loading = batchListParams.current.total <= batchList.length;

  }, [batchList.length])




  const onPopupScroll = async (e: any) => {
    const { clientHeight, scrollHeight, scrollTop } = e.target
    console.log(!batchListParams.current.loading)
    if (clientHeight + scrollTop === scrollHeight && !batchListParams.current.loading) {
      //请求
      await selectBatchList(batchListParams.current)
      batchListParams.current.pageStart += 1

    }

  }

  const batchChange = async (value: number) => {
    selectBatch.current = value


  }

  //初始化
  const clearBatchList = async () => {
    batchListParams.current.pageSize = 10;
    batchListParams.current.pageStart = 1;
    batchListParams.current.loading = false;
    batchListParams.current.total = 0;


    const data = await fetchRequest(url.BATCH_SELECT, batchListParams.current)
    if (data.success) {
      setBatchList(data?.importDataBatchVOMyPager?.rows)
      batchListParams.current.total = data?.importDataBatchVOMyPager?.total;
    }
  }


  const submit = async (list: any) => {

    //添加等待loading

    params.current.studentAccessList = list.map((item: any) => ({
      phone: getSecretString(`${item['学生电话号码']}`),
      white_card_code: item['白卡号码'],
      imei: item['IMEI号码']
    }))

    console.log(params.current.collegeId)

    if (params.current.collegeId == '') {
      message.error('请选择学校')
      return
    }


    if (flag.current) {
      message.error('电话号码不正确')
      return
    }

    try {
      setLoading(true)
      await importData()
      await clearBatchList()
    } catch (error) {
      setLoading(false)
    }




  }
  const setFileName = (fileName: any) => {
    params.current.fileName = fileName
  }

  useEffect(() => {
    selectBatchList(batchListParams.current)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const onClose = () => {

    params.current = { ...paramsTemp }

    console.log(1)
    setId(shortid.generate())

  }


  const search = () => (<div className={' search'}>


    <div className={'title'}>请选择已上传文件:</div>
    <div><Select style={{ width: 400 }} onChange={batchChange}
      onPopupScroll={onPopupScroll}>{batchList.map((item: any, index) => (
        <Option value={item.batch} key={index}>{item.fileName}--{item.batch}</Option>))}</Select></div>
    <div className={'btn'}>
      <Button type={'primary'} onClick={selectClick} icon={<SearchOutlined />}>查询</Button>
    </div>

    <div className={'btn'}>
      <Button type={'primary'} onClick={ImportClick} icon={<FallOutlined />}>导入</Button>
    </div>


  </div>)

  const table = () => <>
    <Table className={'table-form'} columns={columns} rowKey="id"     {...tableProps as any} />
  </>


  return <>
    <div className={'wrap bulk import'}>
      {search()}
      {table()}
      <ImportDrawer key={id}
        setData={setData}
        submit={submit} loading={loading} setFileName={setFileName} setSchoolChange={(CollegeAreaItem) => {

          params.current.collegeAreaId = `${CollegeAreaItem.collegeAreaId}`
          params.current.collegeId = `${CollegeAreaItem.collegeId}`

        }} visible={visible} flag={flag} setVisible={setVisible}
        onCloses={onClose}
        data={data}
      />

    </div>
  </>
}

const ImportDrawer: FC<{
  submit: (data: any) => void, setFileName: (data: any) => void, setSchoolChange: (data: any) => void,
  data: any,
  setData: (data: any) => void,
  setVisible: (visible: boolean) => void, visible: boolean, flag: any, onCloses: any
  loading: boolean
}> = ({
  submit,
  setFileName,
  setSchoolChange,
  visible,
  setVisible,
  flag,
  onCloses,
  loading,
  data,
  setData
}) => {


    const columns = [
      {
        title: '学生电话号码',
        key: '学生电话号码',
        dataIndex: '学生电话号码',
        render: (record: any, item: any) => {
          let text = item['学生电话号码']
          const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
          if (!(reg.test(item['学生电话号码']))) {
            text = <Tag color={'#f5222d'}>学生电话号码错误</Tag>
            flag.current = true
          }
          return text
        }
      },
      {
        title: '白卡号码',
        key: '白卡号码',
        dataIndex: '白卡号码',
      },
      {
        title: 'IMEI号码',
        key: 'IMEI号码',
        dataIndex: 'IMEI号码',
      },
    ]


    const input = useRef<HTMLInputElement>(null)

    const [CollegeAreaList, setCollegeAreaList] = useState<ICollegeAreaList[]>([])

    //获取校区
    const getCampusRequest = async () => {

      try {
        const json = await fetchRequest(url.GET_CAMPUS, { collegeAndAreName: '' });
        console.log(json)
        if (json.success) {
          message.destroy();
          setCollegeAreaList(json.data);
        } else {
          message.destroy();
          message.error(json.error);

        }
      } catch (error: any) {
        message.destroy();
        message.error(error.message);
      }
    }

    useEffect(() => {
      (async () => {
        await getCampusRequest()

      }
      )()
    }, [])

    const handleExcelFile = async <T,>(file: File) => {
      let reader = new FileReader();  // 使用 FileReader 读取数据

      return new Promise<T>(((resolve, reject) => {

        reader.onload = function (e) {  // 数据读取完成后的回调函数
          try {

            let workbook = XLSX.read(e.target?.result, { type: 'binary' })
            let firstSheetName = workbook.SheetNames[0];  // 获取第一个 sheet 的名字
            let worksheet = workbook.Sheets[firstSheetName];  // 获取第一个 sheet 的内容
            let res = XLSX.utils.sheet_to_json(worksheet) as unknown as T;  // 使用 utils 里的方法转换内容为便于使用的数组
            console.log(res)
            resolve(res)
          } catch (e) {
            message.error("数据异常！");
            reject(e)
          }
        };
        reader.readAsBinaryString(file);  // 读取数据

      }))


    }

    const fileChange = async (e: ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0]
      flag.current = false

      if (file) {
        const list = await handleExcelFile<any[]>(file)
        // noinspection JSNonASCIINames

        setData(list)
        setFileName(file.name)


      }
    }

    const schoolChange = (value: number) => {
      const CollegeAreaItem = CollegeAreaList.find(item => item.collegeAreaId == value)
      console.log(CollegeAreaItem)
      if (CollegeAreaItem) {

        setSchoolChange(CollegeAreaItem)

      }
    }


    return <Drawer
      title="导入模板"
      placement="right"
      width={800}
      closable={false}
      onClose={() => {
        setVisible(false);

        onCloses()



      }}
      visible={visible}
      destroyOnClose


    >
      <Spin indicator={<LoadingOutlined />} spinning={loading} delay={500} >
        <div className="import-item">
          导入模板:
          <span className={'import-val'}><a href={require('@/excel/门禁批量开通模板.xlsx')}>模板下载</a></span>
        </div>
        <div className={'import-item'}>
          请选择导入学校:
          <span className={'import-val'}>
            <Select style={{ width: 200 }} onChange={schoolChange}>{CollegeAreaList.map((item: any, index) => (
              <Option value={item.collegeAreaId} key={index}>{item.collegeAndArea}</Option>))}</Select>
          </span>


        </div>
        <div className="import-item">
          上传文件:
          <span className={'import-val'}>
            <input type='file' accept='.xlsx, .xls' onChange={fileChange} ref={input} />
          </span>
        </div>
        <div className="import-item">
          数据预览：
          <Table className="import-table" dataSource={data} columns={columns} rowKey={(record: any) => record} />
        </div>

        <div className={'import-btn'}>
          <Button type={'primary'} onClick={() => submit(data)}>提交</Button>
        </div>
      </Spin>


    </Drawer>
  }


export default Index


